package com.eques.demo

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import com.eques.base.BaseActivity
import com.eques.util.Config
import com.eques.util.EquesMytool
import com.eques.util.HttpUtil
import org.json.JSONObject

/**
 * 用户注册界面
 */
class RegisterActivity : BaseActivity() {

    private lateinit var edt_user_name: EditText
    private lateinit var btn_register: Button


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        initView()
        initData()
    }

    override fun initView() {
        edt_user_name = findViewById(R.id.edt_user_name)
        btn_register = findViewById(R.id.btn_register)

        btn_register.setOnClickListener {
            val userName = edt_user_name.text.toString()
            if (userName.isEmpty()) {
                showToast("请输入用户名")
                return@setOnClickListener
            }
            if (userName.length > 10) {
                showToast("用户名不能超过10位")
                return@setOnClickListener
            }
            if (userName.length < 4) {
                showToast("用户名不能小于4位")
                return@setOnClickListener
            }
            val nonce = System.currentTimeMillis() / 1000
            val sign = EquesMytool(this).md5(userName + nonce.toString() + Config.THIRD_APP_SECRET)
            val jsonBody = JSONObject()
            jsonBody.put("id", Config.THIRD_BRAND_ID)
            jsonBody.put("name", userName)
            jsonBody.put("nonce", nonce)
            jsonBody.put("sign", sign)
            val registerUrl = Config.getRegisterUrl(preference.getSubUrl())
            HttpUtil.postJsonAsync(
                url = registerUrl.toString(),
                jsonBody = jsonBody.toString()
            ) { result ->
                result.onSuccess { response ->
                    println("POST Response: $response")
//                    {"code":0,"reason":"success","data":"5b018d514c621b16db87f5fd6b3b7a39"}
                    val jsonObject = JSONObject(response)
                    val code = jsonObject.optInt("code")
                    if (code == 0) {
                        val dataKey = jsonObject.optString("data")
                        //用户登录快捷密码，不建议存储本地，可绑定自有app账号，保存于服务器，登录时使用
                        preference.putString(Config.EQUES_USER_KEY, dataKey)
                        runOnUiThread{
                            finish()
                        }
                    }
                }.onFailure { exception ->
                    println("POST Error: ${exception.message}")
                }
            }
        }
    }


    override fun initData() {

    }

}